<?php

declare(strict_types=1);

namespace App\Common\Models;
use App\Common\Demand\Models\LoginLog as LogInterfaces;
use App\Common\Exception\Store\DataNotFound;
/**
 * @property int $log_id 
 * @property int $target_id 
 * @property int $target_type 
 * @property int $error_number 
 * @property string $last_ip 
 * @property int $last_time 
 * @property \Carbon\Carbon $create_time 
 * @property int $delete_time 
 * @property \Carbon\Carbon $update_time 
 * @property int $status 
 */
class LoginLog extends BaseModel implements LogInterfaces
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'login_log';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = ['target_id','target_type','error_number','login_ip','status'];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = ['log_id' => 'integer', 'target_id' => 'integer', 'target_type' => 'integer', 'error_number' => 'integer', 'create_time' => 'datetime', 'delete_time' => 'integer', 'update_time' => 'datetime', 'status' => 'integer'];
    public function getListPage(array $requestData, array $field=['*']):array{
        $where = function ($q) use ($requestData) {
            $q->where('target_type', '=', $requestData['target_type']);
        };
        $page = $this->utils->getPageLimitData($requestData['page'],$requestData['limit']);
        $order = $this->utils->getSortData($requestData['sort_field'],$requestData['sort_type'],$this->getKeyName());
        $listPage=$this->query()->where($where)->offset($page['start'])->limit($page['limit'])->orderBy($order['field'],$order['type'])->get($field);
        if($listPage->isEmpty()){
            throw new DataNotFound($this->translatorInterface->trans('admin.dataNotFind'));
        }else{
            return $listPage->toArray();
        }
    }
    public function getErrorNumber(int $targetId,int $targetType):int{
        $where=[
            ["target_id","=",$targetId],
            ["target_type","=",$targetType],
            ["status","=",1]
        ];
        return $this->query()->where($where)->count();
    }
    public function updateLogStatus(int $targetId,int $targetType):bool{
        $where=[
            ["target_id","=",$targetId],
            ["target_type","=",$targetType]
        ];
        return (bool)$this->query()->where($where)->update(['status'=>2]);
    }
    public function getLastTime(int $targetId,int $targetType):int{
        $where=[
            ["target_id","=",$targetId],
            ["target_type","=",$targetType],
            ["status","=",1]
        ];
        $row=$this->query()->where($where)->orderBy('log_id','desc')->first();
        if(empty($row)){
            return 0;
        }else{
            return (int)strtotime($row->toArray()['create_time']);
        }
    }
}
